﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace team33_ass3
{
    /// <summary>
    /// MapFile is basically a Reader and Writer to read Map Formats. Custom Map format
    /// </summary>
    static class MapFile
    {
        /* MapFile Structure
         * mapHeight
         * mapWidth
         * 
         * start of all the MapBlocks in the Map
         * 
         * MapBlocks has the format of 
         * xPos
         * yPos
         * width
         * solid
         */

        /// <summary>
        /// Reads a file using Binary
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        static public Map readFile(String fileName)
        {
            using (BinaryReader br = new BinaryReader(File.Open(fileName, FileMode.Open)))
            {
                int mapHeight = br.ReadInt32();
                int mapWidth = br.ReadInt32();

                Map loadMap = new Map(mapWidth, mapHeight);

                for (int i = 0; i < mapWidth; i++)
                {
                    for (int j = 0; j < mapHeight; j++)
                    {
                        int xPos = br.ReadInt32();
                        int yPos = br.ReadInt32();
                        int width = br.ReadInt32();
                        bool solid = br.ReadBoolean();

                        MapBlock tmp = new MapBlock(xPos, yPos, width, solid);
                        loadMap.add(xPos, yPos, tmp);
                    }
                }

                return loadMap;
            }
            
        }

        /// <summary>
        /// Writes the map object into a file.
        /// </summary>
        /// <param name="map"></param>
        /// <param name="fileName"></param>
        static public void writeFile(Map map, String fileName)
        {
            using (BinaryWriter bw = new BinaryWriter(File.Open(fileName, FileMode.Create)))
            {
                MapBlock[,] workingMap = map.getMap();

                int mapHeight = map.MAP_HEIGHT;
                int mapWidth = map.MAP_WIDTH;

                bw.Write(mapHeight);
                bw.Write(mapWidth);

                for (int i = 0; i < map.MAP_WIDTH; i++)
                {
                    for (int j = 0; j < map.MAP_HEIGHT; j++)
                    {
                        MapBlock block = workingMap[i, j];

                        int xPos = block.getX();
                        int yPos = block.getY();
                        int width = block.getWidth();
                        bool solid = block.isSolid();

                        bw.Write(xPos);
                        bw.Write(yPos);
                        bw.Write(width);
                        bw.Write(solid);
                    }
                }
            }
        }

    }
}
